package getTmpIndexs

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

var (
	TmpIndexs []TmpIndex = make([]TmpIndex, 0) //存储临时索引集合
)

//临时索引
type TmpIndex struct {
	TermID int64 //单词编号
	DocID  int64 //所属网页编号
}

// 读取临时索引文件tmp_Index.bin，并将数据写入TmpIndexs
func GetTmpIndexs() {
	fmt.Println("开始读取tmp_Index.bin文件")
	defer func() {
		fmt.Println("终止读取tmp_Index.bin文件")
	}()
	file, err := os.Open("/home/fcou/go/src/SearchEngine/analysis/tmpIndex/tmp_Index.bin")
	if err != nil {
		fmt.Println("file open error:", err)
		return
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	// 循环读取全部文件信息
	for {
		//1.先读取单词编号
		termIDString, err := reader.ReadString('\t')
		if err == io.EOF {
			fmt.Println("error:", err)
			break
		}
		if err != nil {
			fmt.Println(err)
			return
		}
		termIDString = strings.Trim(termIDString, "\t") //注意去除“\t”
		termID, err := strconv.ParseInt(termIDString, 10, 64)
		// fmt.Printf("单词编号是：%s\n", termIDString)
		//2.再读取网页编号
		docIDString, err := reader.ReadString('\r')
		if err != nil {
			fmt.Println(err)
			return
		}
		docIDString = strings.Trim(docIDString, "\r") //注意去除“\r”
		docID, err := strconv.ParseInt(docIDString, 10, 64)
		// fmt.Printf("网页编号是：%s\n", docIDString)
		// 3.创建临时索引对象， 并存入切片
		tmp := TmpIndex{TermID: termID, DocID: docID}
		TmpIndexs = append(TmpIndexs, tmp)
		//5.读取分割符\n
		reader.ReadString('\n')
	}
}
